use crate::models::pages::{self, CreateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;
use serde::Deserialize;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/pages", post(create))
        .route("/pages/:id", get(get_by_id))
        .route("/pages/:id", post(update))
        .route("/pages/:id/delete", post(delete))
        .route("/pages/by-slug/:slug", get(get_by_slug))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let page = pages::Model::create(&state.db, &params).await?;
    format::json(page)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let page = pages::Model::find_by_id(&state.db, &id).await?;
    format::json(page)
}

async fn get_by_slug(
    State(state): State<AppContext>,
    axum::extract::Path(slug): axum::extract::Path<String>,
) -> Result<Response> {
    let page = pages::Model::find_by_slug(&state.db, &slug).await?;
    format::json(page)
}

#[derive(Debug, Deserialize)]
pub struct UpdateParams {
    pub active: bool,
    pub position: i32,
    pub show_breadcrumb: bool,
}

async fn update(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
    Json(params): Json<UpdateParams>,
) -> Result<Response> {
    let page = pages::Model::find_by_id(&state.db, &id).await?;
    let active_model: pages::ActiveModel = page.into();


    format::json(())
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let page = pages::Model::find_by_id(&state.db, &id).await?;
    page.delete(&state.db).await?;
    format::json(())
}
